import 'dart:convert';

import 'package:app/api/account/index.dart';
import 'package:app/components/index.dart';
import 'package:app/util/SecureStorage.dart';
import 'package:flutter/material.dart';

/// 切换账号
class SwitchAccount extends StatefulWidget{

  const SwitchAccount({super.key});

  @override
  State<StatefulWidget> createState()  => _SwitchAccountState();

}

class _SwitchAccountState extends State<SwitchAccount>{

  List<dynamic> _list = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      Account.of(context).userInfo().then((res){
        SecureStorage.of().get("accounts").then((account){
          List<dynamic> accounts = jsonDecode(account);
          dynamic item = accounts.where((e){
            return e['account'] == res.data['data']['account'];
          }).toList();
          accounts.remove(item[0]);
          accounts.insert(0, item[0]);
          setState(() => _list = [...accounts, {'userName': '添加账号'}]);
        });
      });
    });
  }

  /// 删除
  void remove(index){
    Confirm.of(context).show('确认要删除账号', (){
      Navigator.of(context).pop();
      setState((){
        _list.removeAt(index);
        List<dynamic> caches = _list.map((item) => item).toList();
        caches.removeAt(_list.length-1);
        SecureStorage.of().set('accounts', jsonEncode(caches));
      });
    });
  }

  void onTap(index){
    if(index != 0 && index != _list.length - 1){
      Confirm.of(context).show('确认要更换账号么', (){
        Account.of(context).login(_list[index]['account'], _list[index]['password']).then((res){
          SecureStorage.of().set('token', res.data['data']['token']);
          Navigator.of(context).pop();
          Navigator.of(context).pushNamed('/home');
        });
      });
    }else if(index == _list.length - 1){
      Navigator.of(context).pushNamed('/login');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '切换账号',),
      backgroundColor:const Color.fromARGB(255, 245, 245, 245),
      body: ListContainer(
        length: _list.length,
        actions: [
          SlidActions(
              onPressed: remove,
              label: '删除',
              icon: Icons.delete
          )
        ],
        isActions: (index){
          return (index != 0 && index != _list.length - 1);
        },
        children: (index){
          return [
              GestureDetector(
                onTap: ()=>onTap(index),
                child: Item(
                  children: [
                    Circular(
                        width: 60,
                        height: 60,
                        backgroundColor: index != _list.length - 1 ? Colors.white : const Color.fromARGB(255, 245, 245, 245),
                        child: index != _list.length - 1 ?
                        const Icon(Icons.person, size: 50, color: Color.fromARGB(255, 100, 203, 184)) :
                        const Icon(Icons.add, size: 40, color: Color.fromARGB(255, 0, 0, 0),)
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 10, top: index != _list.length - 1 ?  5 : 15),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(_list[index]['userName'], style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),),
                          index != _list.length - 1 ? Text(_list[index]?['account']??'', style: const TextStyle(fontSize: 16)) : Container()
                        ],
                      ),
                    ),
                    index == 0 ? Padding(
                      padding: const EdgeInsets.only(top: 10, left: 10),
                      child: Container(
                        decoration: BoxDecoration(
                            color: const Color.fromARGB(255, 243, 206, 206),
                            borderRadius:  BorderRadius.circular(5)
                        ),
                        child: const Padding(
                          padding: EdgeInsets.only(top: 3, left: 5, right: 5, bottom: 3),
                          child: Text('当前账号', style: TextStyle(color: Colors.red,  fontSize: 13),),
                        ),
                      ),
                    ) : Container()
                  ],
                ),
              )
          ];
        },
      )
    );
  }

}